import { Button, Form, Input, Table, Tag, Tooltip, Typography } from "antd";
import type { ColumnsType } from "antd/es/table";
import { PlusIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { apiChannelList } from "~/api";
import Filter from "~/components/ui/filter";
import CreditCodeDetail from "~/components/ui/manage/channel/list/credit-code-detail";
import Title from "~/components/ui/title";
import { useDictMap } from "~/contexts/dict";
import { useTableHeight } from "~/hooks/useTableHeight";
import type { IPageData } from "~/types/common";
import type { IChannel } from "~/types/manage/channel/list";
import { cn } from "~/utils/ui.util";
import ChannelConfigDrawer from "./manage/channel/list/channel-config-drawer";
import ChannelModal from "./manage/channel/list/channel-modal";

interface IFilter {
  pageNum: number;
  pageSize: number;
  name?: string;
  companyName?: string;
}

export default function Page() {
  const [filterForm] = Form.useForm<IFilter>();
  const [dataList, setDataList] = useState<IPageData<IChannel> | null>(null);
  const tableHeight = useTableHeight(325);
  const [modalVisible, setModalVisible] = useState(false);
  const [editChannel, setEditChannel] = useState<IChannel | null>(null);

  const [configDrawerVisible, setConfigDrawerVisible] = useState(false);
  const [configChannel, setConfigChannel] = useState<IChannel | null>(null);

  const dictMap = useDictMap();

  const _handler = {
    addChannel: () => {
      setModalVisible(true);
      setEditChannel(null);
    },
    editChannel: (channel: IChannel) => {
      setModalVisible(true);
      setEditChannel(channel);
    },
    editChannelConfig: (channel: IChannel) => {
      setConfigDrawerVisible(true);
      setConfigChannel(channel);
    },
  };

  const _ui: {
    tableColumns: ColumnsType<IChannel>;
  } = {
    tableColumns: [
      {
        title: "序号",
        dataIndex: "index",
        key: "index",
        fixed: "left",
        width: 80,
        render: (_, __, index) => {
          return index + 1;
        },
      },
      {
        title: "渠道名称",
        dataIndex: "name",
        key: "name",
        fixed: "left",
        width: 180,
        render: (_, record) => {
          return (
            <div className="flex gap-1">
              {dictMap[record.type]?.label && (
                <Tag color="green">{dictMap[record.type]?.label}</Tag>
              )}
              <Tooltip title="渠道配置">
                <a
                  className="line-clamp-1"
                  onClick={() => _handler.editChannelConfig(record)}
                >
                  {record.name}
                </a>
              </Tooltip>
            </div>
          );
        },
      },
      {
        title: "企业名称",
        key: "companyName",
        width: 240,
        render: (_, record) => {
          return <CreditCodeDetail record={record} />;
        },
      },
      {
        title: "渠道内容配置",
        dataIndex: "channelNovelConfig",
        key: "channelNovelConfig",
        width: 150,
        render: (_, record) => {
          return (
            <div className="flex flex-col gap-2">
              {(record.channelNovelConfig?.kind?.length || 0) > 0 && (
                <div>
                  {record.channelNovelConfig?.kind?.map((item) => (
                    <Tag key={item}>{dictMap[item]?.label || "--"}</Tag>
                  ))}
                </div>
              )}
              {(record.channelNovelConfig?.lengthType?.length || 0) > 0 && (
                <div>
                  {record.channelNovelConfig?.lengthType?.map((item) => (
                    <Tag key={item}>{dictMap[item]?.label || "--"}</Tag>
                  ))}
                </div>
              )}
              {(record.channelNovelConfig?.contentType?.length || 0) > 0 && (
                <div>
                  {record.channelNovelConfig?.contentType?.map((item) => (
                    <Tag key={item}>{dictMap[item]?.label || "--"}</Tag>
                  ))}
                </div>
              )}
            </div>
          );
        },
      },
      {
        title: "渠道后台",
        dataIndex: "backendUrl",
        key: "backendUrl",
        width: 250,
        render: (_, record) => {
          return (
            <div
              className={cn("flex flex-col gap-2", {
                hidden: !record.adminUrl,
              })}
            >
              <a href={record.adminUrl} target="_blank">
                {record.adminUrl}
              </a>
              <span>
                账号：
                <Typography.Text type="secondary">
                  {record.account}
                </Typography.Text>
              </span>
              <span>
                密码：
                <Typography.Text type="secondary">
                  {record.password}
                </Typography.Text>
              </span>
            </div>
          );
        },
      },
      // {
      //   title: "配置",
      //   dataIndex: "config",
      //   key: "config",
      //   width: 150,
      //   render: (value) => {
      //     return <span>{JSON.stringify(value)}</span>;
      //   },
      // },
      // {
      //   title: "开票信息",
      //   dataIndex: "creditCode",
      //   render: (_, record) => {
      //     return <CreditCodeDetail record={record} />;
      //   },
      // },
      {
        title: "合同起止时间",
        dataIndex: "contractTimeRange",
        width: 150,
        render: (_, record) => {
          return (
            <div className="flex flex-col gap-2">
              <span>{record.contractStart || "--"}</span>
              <span>至</span>
              <span>{record.contractExpiry || "--"}</span>
            </div>
          );
        },
      },
      {
        title: "操作",
        width: 80,
        fixed: "right",
        render: (_, record) => {
          return (
            <div className="flex flex-col gap-2">
              <Button
                size="small"
                type="link"
                onClick={() => {
                  _handler.editChannel(record);
                }}
              >
                编辑
              </Button>
            </div>
          );
        },
      },
    ],
  };

  const _fetch = {
    channels: async (params?: IFilter) => {
      const resp = await apiChannelList(params);
      setDataList(resp);
    },
  };

  useEffect(() => {
    _fetch.channels(filterForm.getFieldsValue(true));
  }, []);

  return (
    <>
      <div className="flex h-full flex-col gap-4">
        <Title
          title="渠道管理"
          buttonGroups={[
            <Button
              type="primary"
              onClick={() => {
                _handler.addChannel();
              }}
            >
              <PlusIcon size={18} />
              添加渠道
            </Button>,
          ]}
        />
        <Filter
          form={filterForm}
          initialValues={{
            pageNum: 1,
            pageSize: 100,
          }}
          onSearch={() => {
            _fetch.channels(filterForm.getFieldsValue(true));
          }}
          onReset={() => {
            _fetch.channels(filterForm.getFieldsValue(true));
          }}
        >
          <Form.Item label={"渠道名称"} name={"name"}>
            <Input />
          </Form.Item>
          <Form.Item label={"企业名称"} name={"companyName"}>
            <Input />
          </Form.Item>
        </Filter>

        <div className="flex-1 overflow-hidden">
          <div className="h-full w-full">
            <Table
              size="small"
              scroll={{
                y: tableHeight,
                x: "max-content",
              }}
              rowKey={(record) => record.id}
              columns={_ui.tableColumns}
              dataSource={dataList?.list}
              locale={{
                emptyText: "暂无数据",
              }}
              pagination={{
                showTotal: (total, range) => {
                  return `共 ${total} 条`;
                },
                pageSizeOptions: [10, 20, 50, 100],
                defaultPageSize: 100,
                showSizeChanger: true,
                onChange(page, pageSize) {
                  filterForm.setFieldsValue({
                    pageNum: page,
                    pageSize: pageSize,
                  });
                  _fetch.channels(filterForm.getFieldsValue(true));
                },
                pageSize: dataList?.pageSize,
                current: dataList?.pageNum,
                total: dataList?.total,
              }}
            />
          </div>
        </div>
      </div>
      <ChannelModal
        visible={modalVisible}
        channel={editChannel}
        onCancel={() => {
          setModalVisible(false);
          setEditChannel(null);
        }}
        onOk={() => {
          setModalVisible(false);
          _fetch.channels(filterForm.getFieldsValue(true));
        }}
      />
      <ChannelConfigDrawer
        visible={configDrawerVisible}
        channel={configChannel}
        onClose={() => {
          setConfigDrawerVisible(false);
          setConfigChannel(null);
        }}
      />
    </>
  );
}
